using System;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using System.Xml;
using System.Text.RegularExpressions;
using System.Text;
using System.IO;

namespace Wsp365.Anonymous.Features.AnonymousAccessToBlog
{
    [Guid("c4ef435f-99c3-4c7b-b89c-9fd4d8a1d384")]
    public class AnonymousAccessToBlogEventReceiver : SPFeatureReceiver
    {
        private static string blogIncludeXsl = "<xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\"><xsl:include href=\"{0}/Wsp365/MobileBlog/blog.xsl\"/></xsl:stylesheet>";

        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            SPWeb web = (SPWeb)properties.Feature.Parent;

            for (int i = 0; i < web.Lists.Count; i++)
            {
                SPList list = web.Lists[i];
                if (!list.Hidden)
                {
                    if (list.RootFolder.Url == "Lists/Posts")
                    {
                        SetCustomXsl(list);
                    }
                }
            }
        }

        private void SetCustomXsl(SPList list)
        {
            //Fix meta fields
            for (int i = 0; i < list.Views.Count; i++)
            {
                SPView view = list.Views[i];
                if (view.XslLink == "blog.xsl")
                {
                    view.Xsl = "<![CDATA[" + string.Format(blogIncludeXsl, list.ParentWeb.ServerRelativeUrl) + "]]>"; 
                    view.Update();
                }
            }
        }

        // Uncomment the method below to handle the event raised before a feature is deactivated.

        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            SPWeb web = (SPWeb)properties.Feature.Parent;

            for (int i = 0; i < web.Lists.Count; i++)
            {
                SPList list = web.Lists[i];
                for (int x = 0; x < list.Views.Count; x++)
                {
                    SPView view = list.Views[x];
                    if (view.XslLink == "blog.xsl")
                    {
                        view.Xsl = "";
                        view.Update();
                    }
                }
            }
            web.GetFile("Wsp365/MobileBlog/blog.xsl").Delete();
        }
    }
}
